package heima_bixiangdong.pro_con;

// 多生产多消费，synchronized写法
class Resource2{
    private String name;
    private int num=1;
    private boolean flag;
    public synchronized void set(String name){
        while (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name+num;
        System.out.println(Thread.currentThread().getName()+"......................生产者..."+this.name);
        num++;
        flag = true;
        this.notifyAll();
    }
    public synchronized void out(){
        while (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"....消费者...."+this.name);
        flag = false;
        this.notifyAll();
    }
}

class Producer2 implements Runnable{
    private Resource2 resource2;

    public Producer2(Resource2 resource2) {
        this.resource2 = resource2;
    }

    @Override
    public void run() {
        while (true){
            resource2.set("面包");
        }
    }
}

class Consumer2 implements Runnable{
    private Resource2 resource2;

    public Consumer2(Resource2 resource2) {
        this.resource2 = resource2;
    }

    @Override
    public void run() {
        while (true){
            resource2.out();
        }
    }
}

// 多生产多消费
public class Demo2 {

    public static void main(String[] args) {
        //test1();
        test2();
    }

    private static void test2() {
        Resource2 resource2 = new Resource2();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource2.set("面包");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource2.set("面包");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource2.out();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource2.out();
                }
            }
        }).start();
    }

    private static void test1() {
        Resource2 resource2 = new Resource2();
        Producer2 producer2 = new Producer2(resource2);
        Consumer2 consumer2 = new Consumer2(resource2);

        Thread t1 = new Thread(producer2);
        Thread t2 = new Thread(producer2);
        Thread t3 = new Thread(consumer2);
        Thread t4 = new Thread(consumer2);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
